package com.xteam.web.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.tangkf.utils.CommonUtils;
import com.tangkf.utils.MDFiveEncrypt;
import com.tangkf.utils.bean.BeanHelper;
import com.tangkf.utils.bean.ReqHelper;
import com.xteam.db.page.Page;
import com.xteam.db.page.PageInfo;
import com.xteam.ecsystem.service.admin.SystemLogService;
import com.xteam.ecsystem.utils.ConstantLocation;
import com.xteam.ecsystem.utils.StringUtil;
import com.xteam.purview.entities.PurviewUser;
import com.xteam.purview.entities.PurviewUserFunDatarule;
import com.xteam.purview.entities.PurviewUserRole;
import com.xteam.purview.service.impl.AuthorizationFace;
import com.xteam.purview.service.impl.PurviewUserFace;
import com.xteam.utils.WebTools;
import com.xteam.web.Error;

public class UserController extends PurViewController implements IController {

	private PurviewUserFace		face	= PurviewUserFace.getInstance();
	private AuthorizationFace	aface	= AuthorizationFace.getInstance();
	
	@Autowired
	private SystemLogService logService;

	public UserController() {
		
	}

	/**
	 * 返回当前登录用户信息
	 * @author tangkf ---2012-2-9
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getCurrentUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.setJsonType(request, response);
		Object uo = request.getSession().getAttribute(PurviewUser.PROP_USERID);
		PurviewUser user = (uo != null && uo instanceof PurviewUser) ? (PurviewUser) uo : null;
		String rinfo = "{}";
		if (user != null) {
			rinfo = JSONObject.fromObject(user).toString();
		}
		PrintWriter out = response.getWriter();
		out.println(rinfo);
		return null;
	}

	/**
	 * 密码修改
	 * @author tangkf ---2012-2-10
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView modifyPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.setJsonType(request, response);
		Object uo = request.getSession().getAttribute(PurviewUser.PROP_USERID);
		PurviewUser user = (uo != null && uo instanceof PurviewUser) ? (PurviewUser) uo : null;
		String rinfo = JSONObject.fromObject("{_code:'1',_info:'密码修改失败，请重新登录！'}").toString();
		if (user != null) {
			String oldpwd = ReqHelper.getRequestString(request, "oldpassword");
			String password = ReqHelper.getRequestString(request, "password");
			if (MDFiveEncrypt.getMD5Encode(oldpwd + "").equals(user.getPassword())) {
				user.setPassword(password);
				face.update(user);
				rinfo = JSONObject.fromObject("{_code:'0',_info:'密码修改成功！'}").toString();
			} else {
				rinfo = JSONObject.fromObject("{_code:'1',_info:'密码修改失败，可能是原密码输入错误！'}").toString();
			}
		}

		PrintWriter out = response.getWriter();
		out.println(rinfo);
		return null;
	}

	/**
	 * 登录验证
	 * @author tangkf ---2012-2-10
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.setJsonType(request, response);
		String userId = ReqHelper.getRequestString(request, "userId");
		String password = ReqHelper.getRequestString(request, "password");
		PurviewUser user = face.getUser(userId, password);
		String rinfo = "{}";
		
		if (user != null) {
			rinfo = JSONObject.fromObject(user).toString();
			String logIp = com.xteam.ecsystem.utils.StringUtil.getIpAddr(request);
			String userType = "";
			
			if(PurviewUserFace.superMan.equals(userId)){
				userType = ConstantLocation.SUPERMGR;
			}else if("1".equals(user.getIssys())){
				userType = ConstantLocation.SYSTEMMGR;
			}else{
				userType = ConstantLocation.COMMONMGR;
			}
			
			request.getSession().setAttribute(PurviewUser.PROP_USERID, user);
			request.getSession().setAttribute("operateUser", user.getUname());
			request.getSession().setAttribute("operateIp", logIp);
			request.getSession().setAttribute("operateUType", userType);
			request.getSession().setAttribute("lastLogTime", this.logService.getLastLogTime(userId));
			
			String roleName = "not assignment";
			PurviewUserRole userRole = face.getPurUserRoleByUserId(user.getUserId());
			if (userRole != null && StringUtil.isNotNullOrEmpty(userRole.getRoleName())) {
				roleName = userRole.getRoleName();
			}
			
			request.getSession().setAttribute("roleName", roleName);
			
			this.logService.saveSystemLogs(user.getUname(), logIp, ConstantLocation.LOG_LOGIN_ECS, 
					"login", ConstantLocation.LOG_LOGIN, "PurviewUser");
		}
		
		PrintWriter out = response.getWriter();
		out.println(rinfo);
	}

	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.setJsonType(request, response);
		request.getSession().removeAttribute(PurviewUser.PROP_USERID);
		
		String operateUser = (String)request.getSession().getAttribute("operateUser");
		String operateIp = (String)request.getSession().getAttribute("operateIp");
		
		if(StringUtil.isNotNullOrEmpty(operateUser)){
			this.logService.saveSystemLogs(operateUser, operateIp, ConstantLocation.LOG_LOGINOUT_ECS, 
					"logout", ConstantLocation.LOG_LOGOUT, null);
		}
		
		return null;
	}

	/**
	 * @see cn.mystic.web.former.PurViewController#delete(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.delete(request, response);

		String[] ids = ReqHelper.getRequestStrings(request, "userId[]");
		String lslUser = ReqHelper.getRequestString(request, "lslUser");
		String lslAddress = ReqHelper.getRequestString(request, "lslAddress");
		
		int r = face.delBatch(PurviewUser.class, PurviewUser.PROP_USERID, ids);
		
		this.logService.saveSystemLogs(lslUser, lslAddress, ConstantLocation.LOG_USER_MGR, 
				"delBatch", ConstantLocation.LOG_DELETE, "PurviewUser");
		
		Error er = r > 0 ? Error.create(r + "", "删除用户出错！") : Error.create();
		WebTools.writerJsonToResponse(response, er);
		return null;
	}

	/**
	 * 用户授权
	 * @author tangkf ---2012-2-8
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView setPurview(HttpServletRequest request, HttpServletResponse response) throws Exception {
		setJsonType(request, response);
		String userId = ReqHelper.getRequestString(request, PurviewUser.PROP_USERID);
		String[] funIds = ReqHelper.getRequestStrings(request, "funId[]");
		String[] roleIds = ReqHelper.getRequestStrings(request, "roleId[]");
		String lslUser = ReqHelper.getRequestString(request, "lslUser");
		String lslAddress = ReqHelper.getRequestString(request, "lslAddress");
		String typeId = "1";
		
		int r = aface.addUserFunNodeRelation(userId, funIds, typeId);
		r = aface.addUserRoleRelation(userId, roleIds);
		
		this.logService.saveSystemLogs(lslUser, lslAddress, ConstantLocation.LOG_USER_MGR, 
				"1-addUserFunNodeRelation，2-addUserRoleRelation", 
				ConstantLocation.LOG_SET_USERPUR, "1-PurviewUserFunDatarule，2-PurviewUserRole");

		Error er = r > 0 ? Error.create(r + "", "用户授权出错！") : Error.create();
		WebTools.writerJsonToResponse(response, er);
		return null;
	}

	/**
	 * @author tangkf ---2012-2-8
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getUserRoleRelation(HttpServletRequest request, HttpServletResponse response) throws Exception {
		setJsonType(request, response);

		String userId = ReqHelper.getRequestString(request, PurviewUser.PROP_USERID);
		List<PurviewUserRole> list = aface.getUserRoleRelation(userId);

		PrintWriter out = response.getWriter();
		String data = JSONArray.fromObject(list).toString();
		out.println(data);
		return null;
	}

	/**
	 * @author tangkf ---2012-2-8
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getUserFunNodeRelation(HttpServletRequest request, HttpServletResponse response) throws Exception {
		setJsonType(request, response);

		String userId = ReqHelper.getRequestString(request, "userId");
		List<PurviewUserFunDatarule> list = aface.getUserFunNodeRelation(userId);

		PrintWriter out = response.getWriter();
		String data = JSONArray.fromObject(list).toString();
		out.println(data);

		System.err.println(list);
		return null;
	}
	
	/**
	 * 读取所有用户
	 * @author tangkf  ---2012-2-21
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView findAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.find(request, response);
		PrintWriter out = response.getWriter();
		List<PurviewUser> list	= new ArrayList<PurviewUser>();
		PurviewUser pu	= new PurviewUser();
		pu.setUserId(PurviewUserFace.superMan);
		pu.setUname(PurviewUserFace.superMan);
		pu.setIssys("1");
		pu.setNickName(PurviewUserFace.superMan);
		list.add(pu);
		list.addAll(face.queryAll(PurviewUser.class));
		String data = JSONArray.fromObject(list).toString();
		out.println(data);
		return null;
	}
	

	/**
	 * @see cn.mystic.web.former.PurViewController#find(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public ModelAndView find(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.find(request, response);

		int size = ReqHelper.getRequestInt(request, "size");
		int pageNo = ReqHelper.getRequestInt(request, "pageNo");

		Page page = new PageInfo(size, pageNo + 1);

		PrintWriter out = response.getWriter();
		String data = JSONObject.fromObject(face.query(PurviewUser.class, page)).toString();
		out.println(data);
		return null;
	}

	/**
	 * @see cn.mystic.web.former.PurViewController#save(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.save(request, response);
		String lslUser = ReqHelper.getRequestString(request, "lslUser");
		String lslAddress = ReqHelper.getRequestString(request, "lslAddress");
		String lslType = ConstantLocation.LOG_ADD;
		String lslMethod = "save";

		PurviewUser fn = new PurviewUser();
		BeanHelper.requestToBean(fn, request);
		
		int r = 0;
		if (CommonUtils.isEmpty(fn.getUserId())) {
			r = face.save(fn);
		} else {
			r = face.update(fn);
			lslType = ConstantLocation.LOG_MODIFY;
			lslMethod = "update";
		}
		
		this.logService.saveSystemLogs(lslUser, lslAddress, ConstantLocation.LOG_USER_MGR, 
				lslMethod, lslType, "PurviewUser");
		
		Error er = r > 0 ? Error.create(r + "", "保存用户出错！") : Error.create();
		WebTools.writerJsonToResponse(response, er);
		
		return null;
	}

}
